<template>
  <div class="muDialog">
    <el-dialog
      width="1000"
      title="商品信息"
      :visible.sync="dialogFormVisible"
      @open="open()"
      @close="close()"
    >
      <el-form :model="iformInfo">
        <template v-for="item in formAttr">
          <el-form-item :label="item.name" :label-width="formLabelWidth">
            <!-- 整数 -->
            <el-input
              clearable
              v-if="item.type == 'input' && item.code == 'int'"
              maxlength="5"
              v-model.number="iformInfo[item.attr]"
              autocomplete="off"
            ></el-input>
            <!-- 小数 -->
            <el-input
              clearable
              @keyup.native="onlyFloat(item.attr)"
              v-else-if="
                item.type == 'input' &&
                item.code == 'float' &&
                item.attr != 'discount'
              "
              type="number"
              v-model.number="iformInfo[item.attr]"
              autocomplete="off"
            ></el-input>
            <!-- 折扣 -->
            <div v-else-if="item.attr == 'discount'">
              <el-radio-group v-model="Fdiscount">
                <el-radio :label="0">无折扣</el-radio>
                <el-radio :label="1">有折扣</el-radio>
              </el-radio-group>
              <el-input
                clearable
                @keyup.native="onlyFloat(item.attr)"
                v-if="Fdiscount"
                type="number"
                v-model.number="iformInfo[item.attr]"
                autocomplete="off"
                placeholder="请输入几多少折"
              ></el-input>
            </div>
            <!-- 文字 -->
            <el-input
              clearable
              autosize
              @keyup.native="Limitwords(item.name, item.attr)"
              v-else-if="item.type == 'input'"
              v-model.trim="iformInfo[item.attr]"
              autocomplete="off"
              :type="item.attr == 'brief' ? 'textarea' : ''"
            ></el-input>

            <el-input
              v-else-if="item.type == 'show'"
              disabled
              v-model="iformInfo[item.attr]"
              autocomplete="off"
            ></el-input>

            <!-- 书类别选择 -->
            <!-- <el-select
              v-else-if="item.type == 'select'"
              v-model="iformInfo[item.attr]"
              placeholder="请选择活动区域"
            >
              <el-option
                v-if="item.code == 'bookType'"
                v-for="opt in allBookTypeList"
                :label="opt.typeName"
                :value="opt.typeId"
                :key="opt.typeId"
              ></el-option>
            </el-select> -->

            <el-cascader
              v-else-if="item.type == 'select'"
              v-model="typeArray"
              :options="allBookTypeList"
              :props="{ expandTrigger: 'hover' }"
              @change="handleChange"
            ></el-cascader>

            <el-col v-else-if="item.type == 'datetime'">
              <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="iformInfo[item.attr]"
                style="width: 100%"
                @blur="dateToFormat(item.attr)"
              ></el-date-picker>
            </el-col>
            <!-- :action="`${url}` + `${iformInfo.bookId}`" -->
            <el-upload
              v-else-if="item.type == 'img'"
              class="avatar-uploader"
              :action="url + '/index/upload/' + iformInfo.bookId"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <div class="imgB" v-if="iformInfo[item.attr]">
                <!-- :src="`${url}` + `${iformInfo.coverPhoto}`" -->
                <img class="img avatar" :src="url + iformInfo.coverPhoto" />
                <!-- <el-button
                  type="text"
                  size="mini"
                  @click.stop.prevent="handlePictureCardPreview"
                  >查看</el-button
                > -->
              </div>
              <i v-else class="el-icon-plus avatar-uploader-icon">上传图片</i>
            </el-upload>
            <!-- <el-dialog :visible.sync="dialogImgVisible">
              <img width="100%" :src="iformInfo.coverPhoto" alt="" />
            </el-dialog> -->
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="toDelete">取 消</el-button>
        <el-button type="primary" @click="toSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  onlyNumOnePoint,
  isEmpty,
  dateFormat,
  onlyNumOneDecimal,
} from "@/assets/myjs/function.js";

export default {
  data() {
    return {
      dialogFormVisible: false,
      formLabelWidth: "120px",
      voidFormInfo: [],
      iformInfo: "",
      typeArray: [],
      Fdiscount: 0,
      url: localStorage.getItem("url"),
    };
  },
  props: ["formInfo", "formAttr"],
  computed: {
    allBookTypeList: function () {
      return this.$store.state.bookType.bookTypeList.cascaderList;
    },
  },
  methods: {
    open() {
      this.voidFormInfo = JSON.parse(JSON.stringify(this.formInfo));
      this.iformInfo = JSON.parse(JSON.stringify(this.formInfo));
      // console.log("this.formInfo.typeId", this.formInfo.typeId);
      this.$store.state.bookType.bookTypeList.secondBookTypeList.forEach(
        (item) => {
          if (item.typeId == this.formInfo.typeId) {
            // console.log("item", item);
            this.typeArray.push(item.pid);
            this.typeArray.push(item.typeId);
            // console.log("this.typeArray:", this.typeArray);
          }
        }
      );
      this.Fdiscount =
        this.formInfo.discount > 0 && this.formInfo.discount < 10 ? 1 : 0;
    },
    close() {
      this.typeArray = [];
    },
    changeDialogFormVisible(bool) {
      if (bool) {
        this.dialogFormVisible = bool;
      } else {
        this.dialogFormVisible = this.dialogFormVisible ? false : true;
      }
    },
    setFormInfo(obj, attr) {
      this.iformInfo = obj ? obj : this.iformInfo;
      this.formAttr = attr ? attr : this.formAttr;
    },
    //图片回显
    handleAvatarSuccess(res, file) {
      // console.log("handleAvatarSuccess");
      // console.log(res);
      this.iformInfo.coverPhoto = res.coverPhotoAddr;
      this.iformInfo.bookId = res.bookId;

      // this.$set(this.iformInfo, "coverPhoto", imgPath);
      // console.log(this.iformInfo.coverPhoto);
    },
    //图片上传大小限制
    beforeAvatarUpload(file) {
      // console.log("beforeAvatarUpload");
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },

    // handlePictureCardPreview() {
    //   console.log("handlePictureCardPreview");
    //   // this.dialogImageUrl = file.url;
    //   this.dialogImgVisible = true;
    // },

    toDelete() {
      this.dialogFormVisible = false;
    },
    toSave() {
      let finished = false;
      this.iformInfo.userId = this.$store.state.user.user.userId;

      if (this.iformInfo.discount) {
        this.iformInfo.price = this.iformInfo.discount * this.iformInfo.nprice;
      } else {
        this.iformInfo.price = this.iformInfo.nprice;
      }

      this.formAttr.forEach((item) => {
        if (isEmpty(this.iformInfo[item.attr])) {
          if (item.attr != "discount") {
            this.$message.warning("请填写/选择: " + item.name + "!");

            finished = false;
            // console.log("isEmpty:", item.name);
            // console.log(typeof this.iformInfo[item.attr]);
            // console.log(this.iformInfo[item.attr]);
            throw Error();
          }
        }
        finished = true;
      });
      if (!finished) {
        return;
      }

      this.dialogFormVisible = false;
      this.iformInfo.addedTime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date());
      if (this.Fdiscount == 0) {
        this.iformInfo.discount = 10;
      }
      // console.log("iformInfo", this.iformInfo);
      this.$axios
        .post("sys/book/updateBybookId", this.iformInfo)
        .then((res) => {
          if (res.status == 200) {
            this.iformInfo = JSON.parse(JSON.stringify(this.voidFormInfo));
            this.typeArray = [];
            // console.log("Save -> iformInfo:", this.iformInfo);
            if (res.data.code == 201) {
              this.$message.warning("成功");
            } else {
              this.$message.warning("失败");
            }
          } else {
            this.$message.warning("请求失败");
          }
          // console.log("book/updateBybookId:", res);
        });
    },
    onlyFloat(attr) {
      this.iformInfo[attr] = onlyNumOnePoint(this.iformInfo[attr]);

      if (attr == "nprice" && !isEmpty(this.iformInfo.discount)) {
        this.iformInfo.price = onlyNumOnePoint(
          (this.iformInfo.nprice * this.iformInfo.discount) / 10
        );
      } else if (attr == "discount" || attr == "depreciation") {
        //折扣
        //约束大于>0 & <10
        if (this.iformInfo[attr] >= 10) {
          this.iformInfo[attr] = this.iformInfo[attr] / 10;
        }
        //小数位数为1
        this.iformInfo[attr] = onlyNumOneDecimal(this.iformInfo[attr]);
        // console.log("discount:", this.iformInfo.discount);

        if (!isEmpty(this.iformInfo.nprice) && attr == "discount") {
          this.iformInfo.nprice = onlyNumOnePoint(
            (this.iformInfo.nprice * this.iformInfo.discount) / 10
          );
        }
      } else {
        this.iformInfo[attr] = onlyNumOnePoint(this.iformInfo[attr]);
      }
    },
    imessage(name, attr, wordNum) {
      if (this.iformInfo[attr].length > wordNum) {
        this.iformInfo[attr] = this.iformInfo[attr].slice(0, wordNum);
        this.$message.warning(`${name}不能超过${wordNum}个字`);
      }
    },
    Limitwords(name, attr) {
      switch (attr) {
        case "bookName":
          this.imessage(name, attr, 18);
          break;
        case "brief":
          this.imessage(name, attr, 298);
          break;
        case "isbn":
          this.imessage(name, attr, 18);
          break;
        case "keyword":
          this.imessage(name, attr, 18);
          break;
        case "author":
          this.imessage(name, attr, 28);
          break;
        case "publisher":
          this.imessage(name, attr, 18);
          break;
      }
    },
    dateToFormat(attr) {
      // =>String
      this.iformInfo[attr] = dateFormat("YYYY-mm-dd", this.iformInfo[attr]);
      // console.log("dateToFormat:", this.iformInfo[attr]);
      // console.log(typeof this.iformInfo[attr]);
    },
    handleChange(value) {
      this.iformInfo.typeId = value[value.length - 1];
      console.log(value);
      console.log(typeof value);
      console.log(this.iformInfo.typeId);
    },
  },
};
</script>

<style lang='less' scoped>
.muDialog {
  min-width: 500px;
}
.el-dialog {
  min-width: 600px;
}
.imgB {
  display: inline;
  width: 100px;
  height: 120px;
  .img {
    width: 100px;
    max-height: 100px;
  }
}
</style>